package com.partner.match.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.partner.match.model.entity.User;
import com.partner.match.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: jzz
 * @CreateTime: 2025-01-22
 * @Description: 定时任务，预热缓存
 */
@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    private List<Long> mainUserList = Arrays.asList(1L,2L);

    @Scheduled(cron = "0 10 0 * * *")
    public void preCacheUser() {
        RLock lock = redissonClient.getLock("user:recommend:precache:lock");
        try {
            boolean tryLock = lock.tryLock(0, 30000, TimeUnit.MILLISECONDS);
            if (tryLock) {
                for (Long userId : mainUserList) {
                    QueryWrapper<User> userQW = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), userQW);
                    String redisKey = String.format("user:recommend:%s", userId);
                    try {
                        redisTemplate.opsForValue().set(redisKey,userPage,1, TimeUnit.MINUTES);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }

            }
        } catch (InterruptedException e) {
            log.error("preCacheUser use redisson to get lock fail", e);
        }finally {
            // 只能释放自己的锁
            if(lock.isHeldByCurrentThread()){
                // 释放锁
                lock.unlock();
            }
        }

    }
}
